package com.kaibes.web.feign;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Collection;

import org.springframework.http.ResponseEntity;

import com.kaibes.web.response.ResponseFactory;

import feign.Response;

@SuppressWarnings("serial")
public class FeignException extends RuntimeException {
	
	private Response response;
	private ResponseEntity<Object> entity;
	
	private String message;
	private String code;
	private String redirect;
	
	public static String urlDecode(String message) {
        try {
            return URLDecoder.decode(message, "utf-8");
        } catch (UnsupportedEncodingException e) {
            return message;
        }
    }
	
	public FeignException(Response response) {
		Collection<String> messageList = response.headers().get(ResponseFactory.MESSAGE);
		Collection<String> codeList = response.headers().get(ResponseFactory.CODE);
		Collection<String> redirectList = response.headers().get(ResponseFactory.REDIRECT);
		
		if (messageList != null) {
			for (String message : messageList) {
				this.message = message;
			}
		}
		if (codeList != null) {
			for (String code : codeList) {
				this.code = code;
			}
		}
		if (redirectList != null) {
			for (String redirect : redirectList) {
				this.redirect = redirect;
			}
		}
		
		entity = ResponseFactory.status(response.status(), code, redirect, getMessage());
	}
	
	public Response getResponse() {
		return response;
	}
	
	public ResponseEntity<Object> getEntity() {
		return entity;
	}
	
	@Override
	public String getMessage() {
	    if (message == null) {
            return null;
        }
		return urlDecode(message);
	}
	
	public String getCode() {
		return code;
	}
	
	public String getRedirect() {
		return redirect;
	}
	
}
